// pages/custom/custom.js
var upload = require('../../utils/upload.js');
var md5 = require('../../utils/md5.js');
var Downloads = require('../../utils/downloads.js')
Page({
  data: {
    hash: {},
    hidden: false,
    loadingText: '素材准备中...',
    multiDownNum: 0,
    minCanvasH: 333,
    minCanvasW: 333,
    canvas: {},
    finalCanvas: {},
    comp: {
      signW: 192,
      signH: 177
    },
    imgSrc: '',
    touch: {
      x: 0,
      y: 0
    },
    coordinates: {
      x: 0,
      y: 0
    },
    downImages: {
      pattern: {},
      border: {},
      sign: {},
      mask: {}
    },
    uploadImages: {
      pattern: {},
      logo: {}
    },
    priviewImages: {},//预览图片
    exportFlag: true,
    customOpt: '0',
    setOpt: '1',//自定义配置
    props: {},
    baseAttr: {
      location: 'simao',
      teatype: 'simao-qiaomu',
      typeName: '思茅-乔木生茶',
      weight: '357',
      amount: 49,
      totalAmount: 325,
      quantity: 7
    },
    drawElem: {
      pattern: {
        url: 'https://www.ynittc.cn/resources/frontPage/images/custom/background/frontward.png',
        node: 'none',
        x: 0,
        y: 0,
        ischange: false
      },
      border: {
        url: '',
        node: '',
        x: 0,
        y: 0,
        ischange: false
      },
      logo: {
        url: '',
        node: '',
        x: 200,
        y: 100,
        w: 53,
        h: 53,
        ischange: false
      },
      sign: {
        url: 'https://www.ynittc.cn/resources/frontPage/images/custom/sign/background.png',
        node: '',
        text: '云茶国际',
        x: 115,
        y: 115,
        w: 99,
        h: 99,
        ischange: false
      },
      teatype: {
        color: '#000000',
        text: '思茅-乔木生茶',
        x: 136,
        y: 260,
        w: 80,
        h: 20,
        size: 9
      },
      gushu: {
        url: 'https://www.ynittc.cn/resources/frontPage/images/custom/background/flag/gushu.png',
        node: '',
        x: 122,
        y: 220,
        w: 82,
        h: 26,
        istrue: false
      },
      weight: {
        color: '#000000',
        weight: '357',
        x: 136,
        y: 280,
        w: 60,
        h: 20,
        size: 9
      },
      skuName: {
        text: '云茶定制示例',
        color: '#000000',
        x: 105,
        y: 70,
        w: 100,
        h: 30,
        size: 22
      },
      corpName: {
        text: '您可调整各项定制参数',
        color: '#000000',
        x: 113,
        y: 90,
        w: 60,
        h: 30,
        size: 11
      },
      copyright: {
        text: '云南国际茶叶交易中心 出品',
        color: '#000000',
        x: 118,
        y: 310,
        size: 8
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取分享参数
    this.setData({
      hash: options
    }),

    //获取所有属性配置
    this.getProps();
    //获取系统高度/宽度
    /**  需要固定宽和高，等比例缩放图片大小
    wx.getSystemInfo({
      success: function (res) {
        //宽度-60px(左右padding) ,高度设为与宽度一致
        that.data.canvasW = res.windowWidth -50;
        that.setData({
          canvasH:that.data.canvasW,
          canvasW:that.data.canvasW
        })
      }
    })
    */
    wx.setNavigationBarTitle({
      title: '专属定制'
    })
  },
  //优化初始化方法
  loadContextNew:function(){
    console.log("start is " + new Date());
    let that = this;
    //第一步创建个上下文容器
    const canvas = wx.createCanvasContext('teaCanvas');
    that.setData({
      canvas: canvas
    })
    //使用download组件
    let downloads = new Downloads();

    //pattern 背景图下载
    for (let i in this.data.props.patternImgL) {
      let item = this.data.props.patternImgL[i];
      if ('none' == item.key) {
        item.url = 'https://www.ynittc.cn/resources/frontPage/images/custom/background/frontward.png';
        downloads.addFile(0,item.url,'downImages.pattern.' + item.key + '.url');
        downloads.addFile(1,item.url,'drawElem.pattern.url');
        //还要写一个值 that.data.drawElem.pattern.url = res.tempFilePath;
      } else {
        item.url = 'https://www.ynittc.cn/resources/frontPage/images/custom/background/pattern/' + item.key;
        downloads.addFile(1,item.url,'downImages.pattern.' + item.key + '.url');
      }
    }

    //border 背景图下载
    for (let i in this.data.props.borderImgL) {
      let item = this.data.props.borderImgL[i];
      item.url = 'https://www.ynittc.cn/resources/frontPage/images/custom/background/border/' + (item.key.substr(3, item.key.length));
      downloads.addFile(1,item.url,'downImages.border.' + item.key + '.url');
    }
    //sign 背景图下载
    downloads.addFile(1,that.data.drawElem.sign.url,'drawElem.sign.url');
    //gushu 古树茶标记下载
    downloads.addFile(1,that.data.drawElem.gushu.url,'drawElem.gushu.url');
    //下载遮罩层 
    downloads.addFile(1,'https://www.ynittc.cn/bizportal/static/app/assets/img/custom/background/mask.png','downImages.mask.url');

    //开始下载
    downloads.startup(function(res){//所有文件下载完成
      if(typeof(res)!='undefined'&&res.length>0){
        for(let i = 0;i<res.length;i++){
          let param = res[i].fileName;
          that.setData({
            [param]:res[i].resUrl
          })
        }
      }
      console.log('allFile downloaded.date is ' + new Date());
      console.log(res);
    },
    function(resp){//优先级为0的文件下载完成
      if(typeof(resp)!='undefined'&&resp.length>0){
        for(let i = 0;i<resp.length;i++){
          let param = resp[i].fileName;
          that.setData({
            [param]:resp[i].resUrl
          })
        }
      }
      that.initFinal();
      console.log('priorityFiles downloaded.date is ' + new Date());
      console.log(resp);
    });

  },
  
  //初始化页面（下载相关图片，否则canvas画图有问题，微信canvas的drawImage需要将图片下载完成后才能画出来，另外，画的顺序也会受影响）
  loadContext: function () {
    let that = this;
    //第一步创建个上下文容器
    const canvas = wx.createCanvasContext('teaCanvas');
    that.setData({
      canvas: canvas
    })
    //pattern 背景图下载
    for (let i in this.data.props.patternImgL) {
      let item = this.data.props.patternImgL[i];
      if ('none' == item.key) {
        item.url = 'https://www.ynittc.cn/resources/frontPage/images/custom/background/frontward.png';
      } else {
        item.url = 'https://www.ynittc.cn/resources/frontPage/images/custom/background/pattern/' + item.key;
      }
      this.downNum(1);//下载数量+1
      wx.downloadFile({
        url: item.url,
        success: function (res) {
          let obj = {};
          obj.url = res.tempFilePath;
          obj.key = item.key;
          obj.value = item.value;
          that.data.downImages.pattern[item.key] = obj;
          //item.url = res.tempFilePath;
          that.setData({
            downImages: that.data.downImages
          })
          if ('none' == item.key) {
            that.data.drawElem.pattern.url = res.tempFilePath;
            that.setData({
              drawElem: that.data.drawElem
            })
          }
          that.downNum(-1);
        }
      })
    }

    this.downResource();    
  },
  //下载其他资源
  downResource: function () {
    let that = this;
    if (this.data.multiDownNum > 2) {
      setTimeout(function(){
        that.downResource();
      },1000)
    }else{
      //border 背景图下载
      for (let i in this.data.props.borderImgL) {
        let item = this.data.props.borderImgL[i];
        item.url = 'https://www.ynittc.cn/resources/frontPage/images/custom/background/border/' + (item.key.substr(3, item.key.length));
        that.downNum(1);//下载数量+1
        wx.downloadFile({
          url: item.url,
          success: function (res) {
            let obj = {};
            obj.url = res.tempFilePath;
            obj.key = item.key;
            obj.value = item.value;
            that.data.downImages.border[item.key] = obj;
            //item.url = res.tempFilePath;
            that.setData({
              downImages: that.data.downImages
            })
            that.downNum(-1);
          }
        })
      }

      //sign 背景图下载
      this.downNum(1);//下载数量+1
      wx.downloadFile({
        url: that.data.drawElem.sign.url,
        success: function (res) {
          that.data.drawElem.sign.url = res.tempFilePath;
          that.downNum(-1);
          that.setData({
            drawElem: that.data.drawElem
          })
        }
      })

      //gushu 古树茶标记下载
      this.downNum(1);//下载数量+1
      wx.downloadFile({
        url: that.data.drawElem.gushu.url,
        success: function (res) {
          that.data.drawElem.gushu.url = res.tempFilePath;
          that.downNum(-1);
          that.setData({
            drawElem: that.data.drawElem
          })
        }
      })

      //下载遮罩层 
      this.downNum(1);//下载数量+1
      wx.downloadFile({
        url: 'https://www.ynittc.cn/bizportal/static/app/assets/img/custom/background/mask.png',
        success: function (res) {
          that.data.downImages.mask.url = res.tempFilePath;
          that.downNum(-1);
          that.setData({
            downImages: that.data.downImages
          })
        }
      })
      this.initFinal();
    }
  },
  //初始化最后一步
  initFinal:function(){
     let that = this;
    if (this.data.multiDownNum > 0) {
      setTimeout(function(){
        that.initFinal();
      },1000)
    }else{
      //初始化计算价格
      this.computePrice();

      that.setData({
        hidden: true
      })
      //初始化页面属性

      for (let o in that.data.props.patternImgL) {
        if (that.data.props.patternImgL[o].key == 'none') {
          that.data.props.patternImgL[o].checked = true;
        }
      }
      //初始化边框
      for (let o in this.data.props.borderImgL) {
        if (this.data.props.borderImgL[o].key == 'none') {
          this.data.props.borderImgL[o].checked = true;
        }
      }
      that.setData({
        props: that.data.props,
        drawElem: that.data.drawElem
      })
      //初始化转发属性
      if (typeof (this.data.hash.type) != "undefined") {
        that.convertToLocal();
      } else {
        that.drawImg();
        that.setData({
          hidden: true
        })
      }
    }
  },
  downNum: function (num) {
    this.data.multiDownNum = this.data.multiDownNum + num;
    this.setData({
      multiDownNum: this.data.multiDownNum
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  expotrIms: function () {
    this.setData({
      exportFlag: false
    })
    wx.canvasToTempFilePath({
      destWidth: 1000,
      destHeight: 1000,
      canvasId: 'finalCanvas',
      success: function (res) {
      }
    })
    var that = this;
  },
  touchstart: function (e) {
    this.data.touch.x = e.touches[0].x;
    this.data.touch.y = e.touches[0].y;
    this.setData({
      touch: this.data.touch
    })
  },
  touchmove: function (e) {
    let x = e.touches[0].x - this.data.touch.x;
    let y = e.touches[0].y - this.data.touch.y;
    this.data.coordinates.x = x;
    this.data.coordinates.y = y;
    this.setData({
      coordinates: this.data.coordinates
    })
    this.data.finalcanvas.moveTo(x, y);
  },
  designOpt: function (e) {
    var clickTab = e.currentTarget.dataset.opt;
    if (clickTab == this.data.customOpt)
      return;
    this.setData({
      customOpt: clickTab
    })
  },
  setOpt: function (e) {
    var clickTab = e.currentTarget.dataset.opt;
    if (clickTab == this.data.setOpt)
      return;
    this.setData({
      setOpt: clickTab
    })
  },
  getProps: function () {
    let that = this;
    wx.request({
      url: getApp().globalData.host + 'custom/customProps',
      header: getApp().globalData.header,
      method: 'POST',
      success: function (res) {
        if (null != res.data && typeof (res.data) != 'undefined') {
          let map = res.data;
          for (var attrs in map) { //遍历map属性
            let arr = [];
            for (var p in map[attrs]) {//将属性转换为List
              let obj = { "key": p, "value": map[attrs][p] };
              arr.push(obj);
            }
            let listName = attrs + 'L';
            map[listName] = arr;
          }
          that.setData({
            props: map
          });
        }
      },
      fail: function (res) { },
      complete: function (res) {
        //准备页面元素
        that.loadContext();
        //that.loadContextNew();
      }
    })
  },
  //变更选择项
  chooseItem: function (e) {
    var itemType = e.currentTarget.dataset.itemType;
    var itemName = e.currentTarget.dataset.itemName;
    var itemNode = e.currentTarget.dataset.itemNode;
    for (var item in this.data.props[itemType]) {
      if (this.data.props[itemType][item].checked && this.data.props[itemType][item].key != itemName) {
        this.data.props[itemType][item].checked = false;
      }
      if (this.data.props[itemType][item].key == itemName && !this.data.props[itemType][item].checked) {//需要重新绘制
        this.data.props[itemType][item].checked = true;
        this.data.drawElem[itemNode].node = itemName;
        this.data.drawElem[itemNode].url = this.data.downImages[itemNode][itemName].url;
      }
    }
    if ("uploadCustomImg" == itemName) { //处理上传图片
      this.data.uploadImages[itemNode].checked = true;
      this.data.drawElem[itemNode].node = itemName;
      this.data.drawElem[itemNode].url = this.data.uploadImages[itemNode].url;
    } else if ("pattern" == itemNode) {
      this.data.uploadImages[itemNode].checked = false;
    }
    /**  this.chooseItem[itemType][itemName].checked = true; **/
    this.setData({
      props: this.data.props,
      drawElem: this.data.drawElem,
      uploadImages: this.data.uploadImages
    })
    this.drawImg();
  },
  //上传使用logo
  uploadLogo: function () {
    upload.uploadFrontPreview(this, 'uploadLogoFinish');
  },
  uploadLogoFinish: function (res) {
    this.data.uploadImages.logo.url = res.temp;
    this.data.uploadImages.logo.serverUrl = JSON.parse(res.data);
    this.data.drawElem.logo.url = res.temp;
    this.setData({
      uploadImages: this.data.uploadImages
    });
    this.drawImg();
  },
  //上传底纹
  uploadPattern: function () {
    upload.uploadFrontPreview(this, 'uploadPatternFinish');
  },
  uploadPatternFinish: function (res) {
    //JSON.parse(res.data) 可获取服务器访问路径 /img/fceaa41e463c470fabc971e65e73e99d.jpg
    //res.temp 获取临时路径
    this.data.uploadImages.pattern.url = res.temp;
    this.data.uploadImages.pattern.serverUrl = JSON.parse(res.data);
    this.data.uploadImages.pattern.checked = true;
    for (var item in this.data.props.patternImgL) {//处理选中事件
      if (this.data.props.patternImgL[item].checked)
        this.data.props.patternImgL[item].checked = false;
    }
    this.setData({
      uploadImages: this.data.uploadImages,
      props: this.data.props
    });
  },
  //加载完成，计算背景长宽高
  patternImageLoad: function (e) {
    let w = e.detail.width;
    let h = e.detail.height;
    let x, y;
    if (w > h) {//宽大于高
      h = (this.data.minCanvasW / w) * h;
      w = this.data.minCanvasW;
      x = 0;
      y = (this.data.minCanvasH - h) / 2;
    } else {//高大于宽
      w = (this.data.minCanvasH / h) * w;
      h = this.data.minCanvasH;
      x = (this.data.minCanvasW - w) / 2;
      y = 0;
    }
    this.data.drawElem.pattern.node = 'uploadCustomImg';
    this.data.drawElem.pattern.url = this.data.uploadImages.pattern.url;
    this.data.drawElem.pattern.x = x;
    this.data.drawElem.pattern.y = y;
    this.data.drawElem.pattern.w = w;
    this.data.drawElem.pattern.h = h;
    this.setData({
      drawElem: this.data.drawElem
    });
    this.drawImg();
  },
  setItem: function (e) {
    var itemName = e.currentTarget.dataset.itemName;
    var itemNode = e.currentTarget.dataset.itemNode;
    if (!("gushu" == itemNode && !this.data.drawElem.gushu.istrue)) {
      this.data.drawElem[itemNode].node = itemName;
    }
    this.setData({
      drawElem: this.data.drawElem
    })
    this.drawImg();
  },
  setItemAttr: function (e) {
    var itemValue = e.currentTarget.dataset.itemValue;
    var itemNode = e.currentTarget.dataset.itemNode;
    var itemAttr = e.currentTarget.dataset.itemAttr;
    this.data.drawElem[itemNode][itemAttr] = itemValue;
    this.setData({
      drawElem: this.data.drawElem
    })
    this.drawImg();
  },
  setBaseAttr: function (e) {
    var itemValue = e.currentTarget.dataset.itemValue;
    var itemNode = e.currentTarget.dataset.itemNode;
    var itemAttr = e.currentTarget.dataset.itemAttr;
    this.data.baseAttr[itemAttr] = itemValue;
    this.data.drawElem[itemNode][itemAttr] = itemValue;
    this.setData({
      baseAttr: this.data.baseAttr,
      drawElem: this.data.drawElem
    })
    this.computePrice();
    this.drawImg();
  },
  setItemType: function (e) {
    var itemValue = e.currentTarget.dataset.itemValue; //类型
    var itemAttr = e.currentTarget.dataset.itemAttr; //中文描述
    var itemGushu = e.currentTarget.dataset.itemGushu; //是否为古树茶
    this.data.baseAttr.teatype = itemValue;
    this.data.baseAttr.typeName = itemAttr;
    this.data.drawElem.teatype.text = itemAttr;
    if (typeof (itemGushu) != "undefined" && null != itemGushu && itemGushu.length > 0) {
      this.data.drawElem.gushu.node = 'true';
      this.data.drawElem.gushu.istrue = true;
    } else {
      this.data.drawElem.gushu.node = '';
      this.data.drawElem.gushu.istrue = false;
    }
    this.setData({
      baseAttr: this.data.baseAttr,
      drawElem: this.data.drawElem
    })
    this.computePrice();
    this.drawImg();
  },
  computePrice: function () {
    let attrName = this.data.baseAttr.teatype + '-' + this.data.baseAttr.weight;
    this.data.baseAttr.amount = this.data.props.price[attrName];
    this.setData({
      baseAttr: this.data.baseAttr
    })
    this.effectPrice();
  },
  //改变文字内容
  inputContent: function (e) {
    var itemNode = e.currentTarget.dataset.itemNode;
    var text = e.detail.value;
    this.data.drawElem[itemNode].text = text;
    this.setData({
      drawElem: this.data.drawElem
    })
    this.drawImg();
  },
  //x轴拖动事件
  xchange: function (e) {
    var itemNode = e.currentTarget.dataset.itemNode;
    this.data.drawElem[itemNode].x = e.detail.value;
    this.changeCoordinate();
  },
  //点击按钮移动，每次5px
  xchangeSub: function (e) {
    var itemNode = e.currentTarget.dataset.itemNode;
    if (this.data.drawElem[itemNode].x == 0) return;
    this.data.drawElem[itemNode].x = this.data.drawElem[itemNode].x - 5;
    this.changeCoordinate();
  },
  xchangeAdd: function (e) {
    var itemNode = e.currentTarget.dataset.itemNode;
    if ((this.data.drawElem[itemNode].x + this.data.drawElem[itemNode].w + 5) > this.data.minCanvasW) return;
    this.data.drawElem[itemNode].x = this.data.drawElem[itemNode].x + 5;
    this.changeCoordinate();
  },
  //变更位置
  changeCoordinate: function () {
    this.setData({
      drawElem: this.data.drawElem
    })
    this.drawImg();
  },
  //y轴拖动事件
  ychange: function (e) {
    var itemNode = e.currentTarget.dataset.itemNode;
    this.data.drawElem[itemNode].y = e.detail.value;
    this.changeCoordinate();
  },
  //点击按钮移动，每次5px
  ychangeSub: function (e) {
    var itemNode = e.currentTarget.dataset.itemNode;
    if (this.data.drawElem[itemNode].y == 0) return;
    this.data.drawElem[itemNode].y = this.data.drawElem[itemNode].y - 5;
    this.changeCoordinate();
  },
  ychangeAdd: function (e) {
    var itemNode = e.currentTarget.dataset.itemNode;
    if ((this.data.drawElem[itemNode].y + this.data.drawElem[itemNode].h + 5) > this.data.minCanvasH) return;
    this.data.drawElem[itemNode].y = this.data.drawElem[itemNode].y + 5;
    this.changeCoordinate();
  },
  //模拟sleep d 休眠毫秒数
  sleep: function (d) {
    for (var t = Date.now(); Date.now() - t <= d;);
  },
  /** 
  * 画图方法,按this.data.drawElem配置顺序绘制图片
  * 当遇到节点ischange = true 时，重新绘制该节点以及该节点以后的元素
  * update ,所有操作均需要重新绘制
  */
  drawImg: function () {
    for (var o in this.data.drawElem) {
      let drawMethod = 'draw' + o;
      this[drawMethod](this.data.drawElem[o]);
      this.sleep(5);
    }
  },

  drawpattern: function (item) {
    let w = this.data.minCanvasW;
    let h = this.data.minCanvasH;
    let x = 0;
    let y = 0;
    //1.先画底图
      this.data.canvas.drawImage(this.data.downImages.pattern.none.url, x, y, w, h);
      this.data.canvas.draw();
      this.sleep(10);
    if ("uploadCustomImg" == item.node) {//自定义底纹
      //2.再画自定义图片
      w = item.w;
      h = item.h;
      x = item.x;
      y = item.y;
      this.data.canvas.drawImage(item.url, x, y, w, h);
      this.data.canvas.draw(true);
      this.sleep(20);
      //3 剪裁多余部分 盖上透明盖子.
      this.data.canvas.drawImage(this.data.downImages.mask.url, 0, 0, this.data.minCanvasW, this.data.minCanvasH);
      this.data.canvas.draw(true);
    } else {
      this.data.canvas.drawImage(item.url, x, y, w, h);
      this.data.canvas.draw(true);
    }
  },
  drawborder: function (item) {
    if ('none' != item.node && item.node.length > 0) {
      this.data.canvas.drawImage(item.url, item.x, item.y, this.data.minCanvasW, this.data.minCanvasH);
      this.data.canvas.draw(true);
    }
  },
  //绘制logo
  drawlogo: function (item) {
    if ('true' == item.node) {
      this.data.canvas.drawImage(item.url, item.x, item.y, item.w, item.h);
      this.data.canvas.draw(true);
    }
  },
  drawsign: function (item) {
    if ('true' == item.node) { //'true'绘制印章
      var that = this;
      that.data.canvas.drawImage(item.url, item.x, item.y, item.w, item.h);
      that.data.canvas.draw(true);
      that.sleep(10);
      //写字
      that.data.canvas.setFillStyle('#FFFFFF');
      that.data.canvas.setFontSize(30);
      that.data.canvas.setTextAlign('center')
      for (var i = 1; i <= Math.ceil(item.text.length / 2); i++) {
        let maxlength = item.text.length < (i * 2) ? item.text.length : i * 2;
        that.data.canvas.fillText(item.text.substr((i - 1) * i, maxlength), item.x + 48, item.y + 40 * i);
        that.data.canvas.draw(true);
        that.sleep(10);
      }
    }
  },
  //产区
  drawteatype: function (item) {
    if (item.text.length > 0) {
      this.data.canvas.setFillStyle(item.color);
      this.data.canvas.setFontSize(item.size);
      this.data.canvas.setTextAlign('left')
      this.data.canvas.fillText(item.text, item.x, item.y);
      this.data.canvas.draw(true);
    }
  },
  //古树
  drawgushu: function (item) {
    if ('true' == item.node && item.istrue) { //'true'绘制古树
      this.data.canvas.drawImage(item.url, item.x, item.y, item.w, item.h);
      this.data.canvas.draw(true);
    }
  },

  //规格
  drawweight: function (item) {
    if (item.weight.length > 0) {
      this.data.canvas.setFillStyle(item.color);
      this.data.canvas.setFontSize(item.size);
      this.data.canvas.setTextAlign('left')
      this.data.canvas.fillText('净含量：' + item.weight + '克', item.x, item.y);
      this.data.canvas.draw(true);
    }
  },
  //文本1
  drawskuName: function (item) {
    if (item.text.length > 0) {
      this.data.canvas.setFillStyle(item.color);
      this.data.canvas.setFontSize(item.size);
      this.data.canvas.setTextAlign('left')
      this.data.canvas.fillText(item.text, item.x, item.y);
      this.data.canvas.draw(true);
    }
  },
  //文本2
  drawcorpName: function (item) {
    if (item.text.length > 0) {
      this.data.canvas.setFillStyle(item.color);
      this.data.canvas.setFontSize(item.size);
      this.data.canvas.setTextAlign('left')
      this.data.canvas.fillText(item.text, item.x, item.y);
      this.data.canvas.draw(true);
    }
  },
  //监制信息
  drawcopyright: function (item) {
    this.data.canvas.setFillStyle(item.color);
    this.data.canvas.setFontSize(item.size);
    this.data.canvas.setTextAlign('center')
    this.data.canvas.fillText(item.text, item.x + 50, item.y);
    this.data.canvas.draw(true);
  },
  reduce: function () {
    if (this.data.baseAttr.quantity < 2) return;
    this.modifyQuantity(-1);
  },
  add: function () {
    this.modifyQuantity(1);
  },
  modifyQuantity: function (num) {
    this.data.baseAttr.quantity = this.data.baseAttr.quantity + num;
    this.setData({
      baseAttr: this.data.baseAttr
    });
    this.effectPrice();
  },
  quantityChange: function (e) {
    var reg = /^[1-9]+[0-9]*]*$/; //判断正整数
    var changetQty = e.detail.value;
    if (reg.test(changetQty)) {
      changetQty = parseInt(changetQty);
      if (changetQty < 0) changetQty = 1;
      if (changetQty > 500) changetQty = 500;

      this.data.baseAttr.quantity = changetQty;
      this.setData({
        baseAttr: this.data.baseAttr
      });
      this.effectPrice();
    } else {
      this.setData({
        baseAttr: this.data.baseAttr
      })
    }
  },
  effectPrice: function () {
    let totalAmount = this.data.baseAttr.quantity * this.data.baseAttr.amount;
    if (this.data.baseAttr.quantity > 6 && this.data.baseAttr.quantity < 14) {
      totalAmount = parseInt(totalAmount * 0.95);
    } else if (this.data.baseAttr.quantity > 13 && this.data.baseAttr.quantity < 42) {
      totalAmount = parseInt(totalAmount * 0.9);
    } else if (this.data.baseAttr.quantity > 41) {
      totalAmount = parseInt(totalAmount * 0.85);
    }
    this.data.baseAttr.totalAmount = totalAmount;
    this.setData({
      baseAttr: this.data.baseAttr
    })
  },
  //手选折扣变更价格
  chooseQuantity: function (e) {
    this.data.baseAttr.quantity = parseInt(e.currentTarget.dataset.quantity);
    this.setData({
      baseAttr: this.data.baseAttr
    })
    this.effectPrice();
  },
  //拨打客服电话
  contactService: function () {
    wx.makePhoneCall({
      phoneNumber: getApp().globalData.servicePhone
    })
  },
  //立即购买
  buyNow: function () {
    let that = this;
    if (getApp().globalData.platUser == null) {//用户未登录 跳转至登录页面
      //let hash = this.convertToHash();
      wx.navigateTo({
        url: '../login/login?returnType=true'
      });
    } else {
      let hash = this.convertToHash();
      wx.request({
        url: getApp().globalData.host + 'custom.html',
        header: getApp().globalData.header,
        data: {
          hash: hash, price: this.data.baseAttr.amount, quantity: this.data.baseAttr.quantity,
          amount: this.data.baseAttr.totalAmount
        },
        method: 'POST',
        success: function (res) {
          if (typeof (res.data.nextUrl) != 'undefined' && res.data.nextUrl.length > 0) {
            let orderId = res.data.nextUrl.substr(res.data.nextUrl.indexOf("orderId=") + 8, res.data.nextUrl.length);
            //先设置为可返回跳转，将来需要修改为不可返回
            wx.navigateTo({
              url: '../confirm/confirm?type=custom&orderId=' + orderId
            });
          }
        }
      })
    }
  },
  //previewImg 预览后台生成大图
  previewImg: function () {
    //预览图片需要登录..访问Biz方法
    if (getApp().globalData.platUser == null) {//用户未登录 跳转至登录页面
      //let hash = this.convertToHash();
      wx.navigateTo({
        url: '../login/login?returnType=true'
      });
    } else {
      //预览图暂存本地previewImg中，key为convertToHash.md5(若无变化，则不请求新的预览图)
      let hash = this.convertToHash();
      //先查询本地缓存
      let md5Name = md5.md5(hash);
      if (this.data.priviewImages[md5Name] != null && typeof (this.data.priviewImages[md5Name].url) != "undefined"
        && this.data.priviewImages[md5Name].url.length > 0) {
        let urls = [];
        urls.push(this.data.priviewImages[md5Name].url);
        wx.previewImage({
          urls: urls
        })
        return;
      }

      //再请求服务器
      let that = this;
      that.setData({
        hidden: false,
        loadingText: '生成图片中...'
      })
      wx.request({
        url: getApp().globalData.host + 'bizportal/my/buyer/customization/previewCustom',
        header: getApp().globalData.header,
        data: { hash: hash },
        method: 'POST',
        success: function (res) {
          if (typeof (res.data) != 'undefined' && res.data.length > 0) {

            wx.downloadFile({
              url: getApp().globalData.host + res.data,
              success: function (res) {
                let obj = {
                  url: res.tempFilePath
                }
                that.data.priviewImages[md5Name] = obj;
                that.setData({
                  priviewImages: that.data.priviewImages,
                  hidden: true
                })
                let urls = [];
                urls.push(that.data.priviewImages[md5Name].url);
                wx.previewImage({
                  urls: urls
                })
              }
            })
          }
        }
      })
    }
  },
  //系统分享入口
  onShareAppMessage: function () {
    let hash = this.convertToHash();
    return {
      title: '[分享] 我的定制茶叶',
      path: '/pages/custom/custom?' + hash.substr(4, hash.length)
    }
  },
  //将配置参数转换为后台参数
  convertToHash: function () {
    let hash = "#!/?";
    let type = "type=" + this.data.baseAttr.teatype + "&type-posY=" + 
      parseInt(this.convertCoordinate(this.data.drawElem.teatype.y, true) - parseInt(this.data.drawElem.teatype.size*2.15)) +
      "&type-size=" + this.convertSize(this.data.drawElem.teatype.size, true) + "&type-posX=" + this.convertCoordinate(this.data.drawElem.teatype.x, true) +
      "&type-font=HeiTi&type-vertical=false&type-color=" + this.convertColor(this.data.drawElem.teatype.color, true);
    let weight = "&weight=" + this.data.baseAttr.weight + "&weight-posY=" + 
      parseInt(this.convertCoordinate(this.data.drawElem.weight.y, true) - parseInt(this.data.drawElem.weight.size*2.15)) +
      "&weight-size=" + this.convertSize(this.data.drawElem.weight.size, true) + "&weight-posX=" + this.convertCoordinate(this.data.drawElem.weight.x, true) +
      "&weight-font=HeiTi&weight-vertical=false&weight-color=" + this.convertColor(this.data.drawElem.weight.color, true);
    let pattern = "&pattern=";
    if (this.data.drawElem.pattern.node == 'uploadCustomImg') { //自定义背景
      pattern = pattern + this.data.uploadImages.pattern.serverUrl;
    } else {
      pattern = pattern + this.convertPattern(this.data.drawElem.pattern.node, true);
    }
    let border = "&border=" + this.convertBorder(this.data.drawElem.border.node, true);
    let sign = "&sign-removed=true";
    if (this.data.drawElem.sign.node == "true") {
      sign = "&sign=" + this.data.drawElem.sign.text + "&sign-posY=" + this.convertCoordinate(this.data.drawElem.sign.y, true) +
        "&sign-font=HeiTi&sign-posX=" + this.convertCoordinate(this.data.drawElem.sign.x, true);
    }
    let skuName = "&skuName=" + this.data.drawElem.skuName.text + "&skuName-posY=" + 
      parseInt(this.convertCoordinate(this.data.drawElem.skuName.y, true) - parseInt(this.data.drawElem.skuName.size*2.15)) +
      "&skuName-posX=" + this.convertCoordinate(this.data.drawElem.skuName.x, true) + "&skuName-size=" + this.convertSize(this.data.drawElem.skuName.size, true) +
      "&skuName-font=HeiTi&skuName-vertical=false&skuName-color=" + this.convertColor(this.data.drawElem.skuName.color, true);
    let corpName = "&corpName=" + this.data.drawElem.corpName.text + "&corpName-posY=" + 
      parseInt(this.convertCoordinate(this.data.drawElem.corpName.y, true) - parseInt(this.data.drawElem.corpName.size*2.15)) +
      "&corpName-size=" + this.convertSize(this.data.drawElem.corpName.size, true) + "&corpName-font=HeiTi&corpName-vertical=false&corpName-color=" +
      this.convertColor(this.data.drawElem.corpName.color, true) + "&corpName-posX=" + this.convertCoordinate(this.data.drawElem.corpName.x, true);
    let logo = "";
    if (this.data.drawElem.logo.node == "true") {
      logo = "&logo=" + this.data.uploadImages.logo.serverUrl + "&logo-posX=" + this.convertCoordinate(this.data.drawElem.logo.x, true) +
        "&logo-posY=" + this.convertCoordinate(this.data.drawElem.logo.y, true);
    }
    let copyright = "&copyright-color=" + this.convertColor(this.data.drawElem.copyright.color, true);
    let gushu = "&flagGushu-removed=true";
    if (this.data.drawElem.gushu.node == "true") {
      gushu = "&flagGushu-posY=" + this.convertCoordinate(this.data.drawElem.gushu.y, true) + "&flagGushu-posX=" +
        this.convertCoordinate(this.data.drawElem.gushu.x, true);
    }
    return hash + type + weight + pattern + border + sign + skuName + corpName + logo + copyright + gushu;
  },
  //将后台参数转换为小程序参数
  convertToLocal: function () {
    if (typeof (this.data.hash.type) != "undefined") {
      var that = this;
      //类型
      this.data.baseAttr.teatype = this.data.hash.type;
      //定义外层循环
      outerloop:
      for (let o in this.data.props) {
        if (o.indexOf("type") > -1) {
          for (let i in this.data.props[o]) {
            if (i == this.data.hash.type) {
              this.data.baseAttr.typeName = this.data.props[o][i];
              this.data.drawElem.teatype.text = this.data.props[o][i];
              break outerloop;
            }
          }
        }
      }
      if(typeof(this.data.hash["type-size"])!="undefined"&&this.data.hash["type-size"].length>0)
        this.data.drawElem.teatype.size = this.convertSize(this.data.hash["type-size"], false);
      if(typeof(this.data.hash["type-posX"])!="undefined"&&this.data.hash["type-posX"].length>0)
        this.data.drawElem.teatype.x = this.convertCoordinate(this.data.hash["type-posX"], false);   
      this.data.drawElem.teatype.y = this.convertCoordinate(parseInt(this.data.hash["type-posY"])+parseInt(this.data.drawElem.teatype.size*2.15), false);
      if(typeof(this.data.hash["type-color"])!="undefined"&&this.data.hash["type-color"].length>0)
        this.data.drawElem.teatype.color = this.convertColor(this.data.hash["type-color"], false);
      

      //规格
      this.data.baseAttr.weight = this.data.hash.weight;
      this.data.drawElem.weight.weight = this.data.hash.weight;
      if(typeof(this.data.hash["weight-size"])!="undefined"&&this.data.hash["weight-size"].length>0)
        this.data.drawElem.weight.size = this.convertSize(this.data.hash["weight-size"], false);
      if(typeof(this.data.hash["weight-posX"])!="undefined"&&this.data.hash["weight-posX"].length>0)
        this.data.drawElem.weight.x = this.convertCoordinate(this.data.hash["weight-posX"], false);
      this.data.drawElem.weight.y = this.convertCoordinate(parseInt(this.data.hash["weight-posY"])+parseInt(this.data.drawElem.weight.size*2.15), false);
      if(typeof(this.data.hash["weight-color"])!="undefined"&&this.data.hash["weight-color"].length>0)
        this.data.drawElem.weight.color = this.convertColor(this.data.hash["weight-color"], false);      
      this.setData({
        drawElem: this.data.drawElem,
        baseAttr: this.data.baseAttr
      })


      //底纹
      let pattern = this.data.hash.pattern;
      if (pattern.indexOf("/img") > -1) { //自定义底纹
        this.downNum(1);//下载数量+1
        wx.downloadFile({
          url: getApp().globalData.host + pattern,
          success: function (res) {
            let resp = {
              data: JSON.stringify(pattern),
              temp: res.tempFilePath
            }
            that.uploadPatternFinish(resp);
            that.downNum(-1);
          }
        })
      } else {
        let patternName = that.convertPattern(pattern, false);

        that.data.drawElem.pattern.node = patternName;
        that.data.drawElem.pattern.url = that.data.downImages.pattern[patternName].url;
        for (let o in that.data.props.patternImgL) {
          if (that.data.props.patternImgL[o].key == patternName) {
            that.data.props.patternImgL[o].checked = true;
          }
          else {
            that.data.props.patternImgL[o].checked = false;
          }
        }
      }
      this.setData({
        drawElem: this.data.drawElem,
        props: this.data.props
      })

      //边框
      let border = this.data.hash.border;
      if (typeof (border) != "undefined" && border != "none" && border.length > 0) {
        let borderName = that.convertBorder(border, false);
        that.data.drawElem.border.node = borderName;
        that.data.drawElem.border.url = that.data.downImages.border[borderName].url;
        for (let o in that.data.props.borderImgL) {
          if (that.data.props.borderImgL[o].key == borderName) {
            that.data.props.borderImgL[o].checked = true;
          }
          else {
            that.data.props.borderImgL[o].checked = false;
          }
        }
        this.setData({
          drawElem: this.data.drawElem,
          props: this.data.props
        })
      }


      //印章
      if (typeof (this.data.hash["sign-removed"]) == "undefined" || !this.data.hash["sign-removed"]) {
        this.data.drawElem.sign.node = "true";
        if(typeof(this.data.hash["sign"])!="undefined"&&this.data.hash["sign"].length>0)
          this.data.drawElem.sign.text = this.data.hash["sign"];
        if(typeof(this.data.hash["sign-posX"])!="undefined"&&this.data.hash["sign-posX"].length>0)
          this.data.drawElem.sign.x = this.convertCoordinate(this.data.hash["sign-posX"], false);
        this.data.drawElem.sign.y = this.convertCoordinate(this.data.hash["sign-posY"], false);
        this.setData({
          drawElem: this.data.drawElem
        })
      }

      //文本1
      let skuName = this.data.hash["skuName"];
      if (typeof (skuName) != "undefined" || skuName.length > 0) {
        this.data.drawElem.skuName.text = skuName;
        if(typeof(this.data.hash["skuName-color"])!="undefined"&&this.data.hash["skuName-color"].length>0)
          this.data.drawElem.skuName.color = this.convertColor(this.data.hash["skuName-color"], false);
        if(typeof(this.data.hash["skuName-size"])!="undefined"&&this.data.hash["skuName-size"].length>0)
          this.data.drawElem.skuName.size = this.convertSize(this.data.hash["skuName-size"], false);
        if(typeof(this.data.hash["skuName-posX"])!="undefined"&&this.data.hash["skuName-posX"].length>0)
          this.data.drawElem.skuName.x = this.convertCoordinate(this.data.hash["skuName-posX"], false);
        this.data.drawElem.skuName.y = this.convertCoordinate(parseInt(this.data.hash["skuName-posY"]) + parseInt(this.data.drawElem.skuName.size*2.15), false);
        this.setData({
          drawElem: this.data.drawElem
        })
      }

      //文本2
      let corpName = this.data.hash["corpName"];
      if (typeof (corpName) != "undefined" || corpName.length > 0) {
        this.data.drawElem.corpName.text = corpName;
        if(typeof(this.data.hash["corpName-color"])!="undefined"&&this.data.hash["corpName-color"].length>0)
          this.data.drawElem.corpName.color = this.convertColor(this.data.hash["corpName-color"], false);
        if(typeof(this.data.hash["corpName-size"])!="undefined"&&this.data.hash["corpName-size"].length>0)
          this.data.drawElem.corpName.size = this.convertSize(this.data.hash["corpName-size"], false);
        if(typeof(this.data.hash["corpName-posX"])!="undefined"&&this.data.hash["corpName-posX"].length>0)
          this.data.drawElem.corpName.x = this.convertCoordinate(this.data.hash["corpName-posX"], false);
        this.data.drawElem.corpName.y = this.convertCoordinate(parseInt(this.data.hash["corpName-posY"]) + parseInt(this.data.drawElem.corpName.size*2.15), false);
        this.setData({
          drawElem: this.data.drawElem
        })
      }


      //logo
      let logo = this.data.hash.logo;
      if (typeof (logo) != "undefined" && logo.indexOf("/img") > -1) { //使用logo
        this.downNum(1);//下载数量+1
        wx.downloadFile({
          url: getApp().globalData.host + logo,
          success: function (res) {
            that.data.uploadImages.logo.url = res.tempFilePath;
            that.data.uploadImages.logo.serverUrl = logo;
            that.data.drawElem.logo.url = res.tempFilePath;
            that.data.drawElem.logo.node = 'true';
            if(typeof(that.data.hash["logo-posX"])!="undefined"&&that.data.hash["logo-posX"].length>0)
              that.data.drawElem.logo.x = that.convertCoordinate(that.data.hash["logo-posX"], false);
            that.data.drawElem.logo.y = that.convertCoordinate(that.data.hash["logo-posY"], false);
            that.setData({
              drawElem: that.data.drawElem,
              uploadImages: that.data.uploadImages
            })
            that.downNum(-1);
          }
        })
      }

      //监制 copyright
      if(typeof(this.data.hash["copyright-color"])!="undefined"&&this.data.hash["copyright-color"].length>0)
        this.data.drawElem.copyright.color = this.convertColor(this.data.hash["copyright-color"], false);
      this.setData({
        drawElem: this.data.drawElem
      })

      //gushu 标记
      let gushu = this.data.hash["flagGushu-removed"];
      if (typeof (gushu) == "undefined" || !gushu) {
        this.data.drawElem.gushu.node = "true";
        this.data.drawElem.gushu.istrue = true;
        if(typeof(this.data.hash["flagGushu-posX"])!="undefined"&&this.data.hash["flagGushu-posX"].length>0)
          this.data.drawElem.gushu.x = this.convertCoordinate(this.data.hash["flagGushu-posX"], false);
        this.data.drawElem.gushu.y = this.convertCoordinate(this.data.hash["flagGushu-posY"], false);
        this.setData({
          drawElem: this.data.drawElem
        })
      }

      this.computePrice();
    }
    this.setData({
      loadingText: "绘制中..."
    })
    this.convertToLocalStep2();
  },
  convertToLocalStep2:function(){
    let that = this;
    if (this.data.multiDownNum > 0) {
      setTimeout(function(){
        that.convertToLocalStep2();
      },1000)
    }else{
      that.drawImg();
      that.setData({
        hidden: true
      })
    }
  },
  //转换pattern flag = true 小程序to后台，false 后台to小程序
  convertPattern: function (value, flag) {
    let result = value;
    if (flag) {
      switch (value) {
        case "shui-wen.png":
          result = "shuiwen";
          break;
        case "flower.png":
          result = "flower";
          break;
        case "mountain.png":
          result = "mountain";
          break;
        case "zhongqiu1.png":
          result = "zhongqiu1";
          break;
        case "zhongqiu2.png":
          result = "zhongqiu2";
          break;
        case "zhongqiu3.png":
          result = "zhongqiu3";
          break;
      }
    } else {
      switch (value) {
        case "shuiwen":
          result = "shui-wen.png";
          break;
        case "flower":
          result = "flower.png";
          break;
        case "mountain":
          result = "mountain.png";
          break;
        case "zhongqiu1":
          result = "zhongqiu1.png";
          break;
        case "zhongqiu2":
          result = "zhongqiu2.png";
          break;
        case "zhongqiu3":
          result = "zhongqiu3.png";
          break;
      }
    }
    return result;
  },
  //转换边框
  convertBorder: function (value, flag) {
    if (typeof (value) == "undefined" || value.length < 3) return value;
    let result = value;
    if (flag) {
      value = value.substr(3, value.length);
      switch (value) {
        case "dan-huan.png":
          result = "danhuan";
          break;
        case "shuang-huan.png":
          result = "shuanghuan";
          break;
        case "pu-tao-hua-teng-1.png":
          result = "putaohuateng1";
          break;
        case "pu-tao-hua-teng-2.png":
          result = "putaohuateng2";
          break;
      }
    } else {
      switch (value) {
        case "danhuan":
          result = "wx_dan-huan.png";
          break;
        case "shuanghuan":
          result = "wx_shuang-huan.png";
          break;
        case "putaohuateng1":
          result = "wx_pu-tao-hua-teng-1.png";
          break;
        case "putaohuateng2":
          result = "wx_pu-tao-hua-teng-2.png";
          break;
      }
    }
    return result;
  },
  //转换sizeto后台size flag = true 小程序to后台，false 后台to小程序
  convertSize: function (value, flag) {
    //小程序<->后台：7<->13,8<->14（copyright无需传字体）,9<->16,11<->20,12<->22,13<->25,16<->30,20<->40
    let result = value;
    if (flag) {
      if (7 == value) result = 13;
      else if (9 == value) result = 16;
      else if (11 == value) result = 20;
      else if (12 == value) result = 22;
      else if (13 == value) result = 25;
      else if (16 == value) result = 30;
      else if (22 == value) result = 40;
    } else {
      if (13 == value) result = 7;
      else if (16 == value) result = 9;
      else if (20 == value) result = 11;
      else if (22 == value) result = 12;
      else if (25 == value) result = 13;
      else if (30 == value) result = 16;
      else if (40 == value) result = 22;
      else if (value > 40) result = 22;
      else if (value > 30 && value < 40) result = 16;
      else if (value > 20 && value < 30) result = 12;
      else result = 9;
    }
    return result;
  },
  //转换坐标 flag = true 小程序to后台，false 后台to小程序
  convertCoordinate: function (value, flag) {
    let result = value;
    if (flag) {
      result = parseInt((value * 600) / 333);
    } else {
      result = parseInt((value * 333) / 600);
    }
    return result;
  },
  //转换颜色 flag = true 小程序to后台，false 后台to小程序
  convertColor: function (value, flag) {
    let result = value;
    if (flag) {
      result = result.substr(1, result.length);
    } else {
      result = "#" + result;
    }
    return result;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})